package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.VatRateDAO;
import mwa.cs.database.Database;
import mwa.cs.model.VatRate;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS11012Srvl
 */
public class CS11011Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
    private Database db; 
	private String vaAgentBrowser;
	private String vaUrlAddress;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11011Srvl() {
        super();
       
    }
    public void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	String vaProcessType = request.getParameter("process_type");
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else{
			getDataTable(request,response);
		
		}
    }
    public void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaStartDate = JDate.saveDate(request.getParameter("startDate"));
		String vaEndDate = JDate.saveDate(request.getParameter("endDate"));
		
		VatRateDAO voVatRateDAO = new VatRateDAO(db);
		try {
			db.beginTransaction();
			voVatRateDAO.deleteVatRateBySiteIdAndStartDateAndEndDate(vnSiteId, vaStartDate, vaEndDate);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11011", JDate.getDate(), JDate.getTime(),vnUserId, "CS11011Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}finally {
			db.close();
		}
		response.getWriter().write("success");
    	
    }
    public void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaStartDate = JDate.saveDate(request.getParameter("startDate"));
		String vaEndDate = JDate.saveDate(request.getParameter("endDate"));
		Double vnRate = Double.parseDouble(request.getParameter("rate"));
		String vaOldStartDate = JDate.saveDate(request.getParameter("oldStartDate"));
		String vaOldEndDate = JDate.saveDate(request.getParameter("oldEndDate"));
		int vnStartDate = Integer.parseInt(vaStartDate);
		int vnEndDate = Integer.parseInt(vaEndDate);
		List<Map<String,Object>> listFindAll;
		VatRateDAO voRateDAO = new VatRateDAO(db);
		listFindAll = voRateDAO.findsCheckStartDateAndEndDateBySite(vnSiteId, vaOldStartDate, vaOldEndDate, vaStartDate, vaEndDate);
		if(vnStartDate > vnEndDate ){
			//System.out.println(vaStartDate+"  More "+vaEndDate);
			response.getWriter().write("StartMoreThanEnd");
		}else if(listFindAll.isEmpty()){
			//not have range
			VatRate poVatRate =new VatRate();
			poVatRate.setVnSiteId(vnSiteId);
			poVatRate.setVnRate(vnRate);
			poVatRate.setVaStartDate(vaStartDate);
			poVatRate.setVaEndDate(vaEndDate);
			poVatRate.setVnInsertUserId(vnUserId);
			poVatRate.setVaUpdateDate(JDate.getDate());
			poVatRate.setVaUpdateTime(JDate.getTime());
			
			VatRateDAO voVatRate = new VatRateDAO(db);
			try {
				db.beginTransaction();
				voVatRate.updateVatRate(vnSiteId, vaOldStartDate,vaOldEndDate, poVatRate);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11011", JDate.getDate(), JDate.getTime(),vnUserId, "CS11011Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}finally{
				db.close();
			}
			response.getWriter();
			
		}else{
			db.close();
			//have range
			response.getWriter().write("have_range");
		}
    }
    
    public void insert(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		this.db = new Database();
		String vaStartDate = JDate.saveDate(request.getParameter("startDate"));
		String vaEndDate = JDate.saveDate(request.getParameter("endDate"));
		Double vnRate = Double.parseDouble(request.getParameter("rate"));
		int vnStartDate = Integer.parseInt(vaStartDate);
		int vnEndDate = Integer.parseInt(vaEndDate);
		List<Map<String,Object>> voListFindAll;
		VatRateDAO voVatRateDAO = new VatRateDAO(db);
		voListFindAll = voVatRateDAO.findCheckStartDateAndEndDateBySite(vnSiteId, vaStartDate, vaEndDate);
		if(vnStartDate > vnEndDate ){
			//System.out.println(vaStartDate+"  More "+vaEndDate);
			response.getWriter().write("StartMoreThanEnd");
		}else if(voListFindAll.isEmpty()){
			//not have range
			//System.out.println(listFindAll+"no have value");
			VatRate poVatRate =new VatRate();
			poVatRate.setVnSiteId(vnSiteId);
			poVatRate.setVnRate(vnRate);
			poVatRate.setVaStartDate(vaStartDate);
			poVatRate.setVaEndDate(vaEndDate);
			poVatRate.setVnInsertUserId(vnUserId);
			poVatRate.setVaInsertDate(JDate.getDate());
			poVatRate.setVaInsertTime(JDate.getTime());
			
			VatRateDAO voRateDAO = new VatRateDAO(db);
			try {
				db.beginTransaction();
				voRateDAO.addVatRate(poVatRate);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11011", JDate.getDate(), JDate.getTime(),vnUserId, "CS11011Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			} finally{
				db.close();
			}
			response.getWriter();
			
		}else{
			//have range
			//System.out.println(listFindAll+"have value");
			db.close();
			response.getWriter().write("have_range");
		}
    }
    
    public void edit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaStartDate = JDate.saveDate(request.getParameter("startDate"));
		
		VatRateDAO voVatRateDAO = new VatRateDAO(db);
		JSONObject voJsonObject = new JSONObject();
		voJsonObject.put("startDate",JDate.showDate(vaStartDate));
		voJsonObject.put("endDate", JDate.showDate(voVatRateDAO.findRateBySiteAndStartDate(vnSiteId, vaStartDate,"END_DATE")));
		voJsonObject.put("rate",voVatRateDAO.findRateBySiteAndStartDate(vnSiteId, vaStartDate, "RATE"));
		
		PrintWriter voOut = response.getWriter();
		
		db.close();
		voOut.print(voJsonObject.toJSONString());
		
    	
    }
    public void getDataTable(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		this.db = new Database();
		VatRateDAO voVatRateDAO = new VatRateDAO(db);
		
		List<Map<String , Object>> voListFindAll ;
		voListFindAll= voVatRateDAO.findVatRateBySite(vnSiteId);
		
		
		
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> voMapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i+1);
			voColumn.add(JDate.showDate((String) voMapItem.get("START_DATE")));
			voColumn.add(JDate.showDate((String) voMapItem.get("END_DATE")));
			voColumn.add(voMapItem.get("RATE"));
			voRow.add(voColumn);
		}
	
			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", voListFindAll.size());
			voObject.put("aaData",voRow);
		
		db.close();
		voOut.print(voObject.toJSONString());
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
